package userSession

import (
	"github.com/samber/lo"
	"strconv"
	"strings"
	"time"
)

// NewReplaceRandomSession 函数提供两种模板变量, 替换username中的变量替换为特定的字符.
// 变量需要使用$包含, 例: $session$.
// session: 替换为 n 个 charset 随机字符.
// expire-min: 替换为分钟.
func NewReplaceRandomSession(n int, charset []rune) UsernameHandler {
	const (
		sessionPlace = "$session$"
		expirePlace  = "$expire-min$"
	)
	return func(username string, expire time.Duration) (string, error) {
		if strings.Contains(username, sessionPlace) {
			username = strings.ReplaceAll(username, sessionPlace, lo.RandomString(n, charset))
		}
		if strings.Contains(username, expirePlace) {
			m := strconv.FormatFloat(expire.Truncate(time.Minute).Minutes(), 'f', 0, 64)
			username = strings.ReplaceAll(username, expirePlace, m)
		}
		return username, nil
	}
}
